// components/search/index.js

import KeyWordModel from '../../models/keyword.js'
import BookModel from '../../models/book.js'
import {paginationBev} from '../behaviors/pagination.js'
const keywordModel = new KeyWordModel()
const bookModel = new BookModel()
Component({
  /**
   * 组件的属性列表
   */
  behaviors:[paginationBev],
  properties: {
    more:{
      type: String,
      observer: '_load_more'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    searching: false,
    inputVal: '',
    loading: false,
    loadingCenter: false
  },
  
  /**
   * 初始化函数
   */
  attached(){
    const historyWords = keywordModel.getHistory()
    const hotWords = keywordModel.getHot()
    
    this.setData({
      historyWords
    })

    hotWords.then(res=>{
      this.setData({
        hotWords: res.hot
      })
    })
    
  },

  /**
   * 组件的方法列表
   */
  methods: {
    _load_more(){

      if (!this.data.inputVal) return
      if(this.data.loading) return

      
      if(this.hasMore()){
        this.setData({
          loading: true
        })
        bookModel.search(this.getCurrentStart(), this.data.inputVal)
          .then(res=>{
            this.setMoreData(res.books)
            this.setData({
              loading: false
            })
          })
      }
    },
    onCancel(event){
      this.triggerEvent("cancel", {

      })
    },
    onDelete(){
      this.setData({
        searching: false
      })
      this.initialize()
    },

    onConfirm(event){
      const word = event.detail.value || event.detail.text
      this._showLoadingCenter()
      this.setData({
        searching: true
      })
      
      bookModel.search(0, word)
        .then(res=>{
          this.setMoreData(res.books)
          this.setTotal(res.total)
          this.setData({
            inputVal: word
          })
          keywordModel.addToHistory(word)
          this._hideLoadingCenter()
        })
    },

    _showLoadingCenter(){
      this.setData({
        loadingCenter: true
      })
    },
    _hideLoadingCenter(){
      this.setData({
        loadingCenter: false
      })
    }
  }
})  
